import useBiliStore from "@/store/modules/useBiliStore";
import $api from "@/api";

function sendWelcomeMsg(value) {
  const biliStore = useBiliStore();
  if (value.action != "enter") return;
  let sendMsg = "";
  if (!biliStore.thanksPlugin.enabled) return;
  if (value.user.identity?.guard_level > 0) {
    sendMsg = biliStore.thanksPlugin.config.welcomeRule.guard.replaceAll(
      "%name%",
      value.user.uname
    );
  } else if (value.user.badge?.active) {
    sendMsg = biliStore.thanksPlugin.config.welcomeRule.fans.replaceAll(
      "%name%",
      value.user.uname
    );
  } else {
    sendMsg = biliStore.thanksPlugin.config.welcomeRule.ordinary.replaceAll(
      "%name%",
      value.user.uname
    );
  }
  console.log("Welcome:", sendMsg);
  $api.bili.sendDanmuMsg(+biliStore.roomId, sendMsg);
}
function sendGiftMsg(value) {
  const biliStore = useBiliStore();
  let sendMsg = "";
  if (!biliStore.thanksPlugin.enabled) return;
  if (value.user.identity?.guard_level > 0) {
    sendMsg = biliStore.thanksPlugin.config.giftRule
      .replaceAll("%name%", value.user.uname)
      .replaceAll("%gift-num%", value.amount)
      .replaceAll("%gift-name%", value.gift_name);
  }
  console.log("Gift:", sendMsg);
  $api.bili.sendDanmuMsg(+biliStore.roomId, sendMsg);
}
function sendGuardMsg(value) {
  const biliStore = useBiliStore();
  let sendMsg = "";
  if (!biliStore.thanksPlugin.enabled) return;
  const guardName = {
    [0]: "",
    [1]: "总督",
    [2]: "提督",
    [3]: "舰长"
  };
  if (value.user.identity?.guard_level > 0) {
    sendMsg = biliStore.thanksPlugin.config.guardRule
      .replaceAll("%name%", value.user.uname)
      .replaceAll("%guard-name%", guardName[value.guard_level]);
  }
  console.log("Guard:", sendMsg);
  $api.bili.sendDanmuMsg(+biliStore.roomId, sendMsg);
}
function sendKeywordsMsg(value) {
  const biliStore = useBiliStore();
  if (!biliStore.replyPlugin.enabled) return;
  biliStore.replyPlugin.config.keywords.forEach(v => {
    let sendMsg = "";
    if (!v.value) return;
    if (!(value.content.trim() == v.key)) return;
    sendMsg = v.value.replaceAll("%name%", value.user.uname);
    console.log("Keywords:", sendMsg);
    $api.bili.sendDanmuMsg(+biliStore.roomId, sendMsg);
  });
}
function sendRegularMsg() {
  const biliStore = useBiliStore();
  if (!biliStore.replyPlugin.enabled) return;
  biliStore.replyPlugin.config.times.forEach((v: any) => {
    if (v._timeId) {
      clearInterval(v._timeId);
      v._timeId = 0;
    }
    v._timeId = setInterval(() => {
      console.log("Regular:", v.value);
      $api.bili.sendDanmuMsg(+biliStore.roomId, v.value);
    }, v.minute * 60 * 1000);
  });
}
function clearRegularMsg() {
  const biliStore = useBiliStore();
  biliStore.replyPlugin.config.times.forEach((v: any) => {
    if (v._timeId) {
      clearInterval(v._timeId);
      v._timeId = 0;
    }
  });
}

export {
  sendWelcomeMsg,
  sendGiftMsg,
  sendGuardMsg,
  sendKeywordsMsg,
  sendRegularMsg,
  clearRegularMsg
};
